#!/bin/bash

port="${1}"
shift 1
url="${1}"
shift 1

if [ -z "${port}" ]
then
    1>&2 echo "usage:"
    1>&2 echo "  ${0} <port> <url> [<option>]"
    exit 1
fi

if [ -z "${url}" ]
then
    1>&2 echo "usage:"
    1>&2 echo "  ${0} <port> <url> [<option>]"
    exit 1
fi

file="$(basename "${url}")"

if [ ! -f "$file" ]
then
  set -x

  # https://rimuhosting.com/knowledgebase/linux/misc/trapping-ctrl-c-in-bash
  
  # trap ctrl-c and call ctrl_c()
  trap ctrl_c INT

  function ctrl_c() {
          echo "** Trapped CTRL-C; cleaning up ${file}.tmp"
          rm -f "${file}.tmp"
  }

  curl --socks5 "localhost:${port}" -f "$url" -o "${file}.tmp" "$@" || rm -f "${file}.tmp"
  if [ ! -s "${file}.tmp" ] ; then
    # .tmp file is empty; delete it
    rm -f "${file}.tmp"
  else
    mv "${file}.tmp" "${file}" 2>/dev/null
  fi
else
  echo "Skipping existing file: $file" 1>&2
fi

